package tw.com.msig.spring.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import tw.com.msig.spring.hibernate.entity.User;
import tw.com.msig.spring.hibernate.service.UserService;

@Controller // <bean id="userController" class="tw.com.msig.spring.web.UserController"/>
@RequestMapping("/users")
public class UserController {
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
			
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/list")
	public String listPage(Model uiModel) {
		
		log.debug("list");
		
		uiModel.addAttribute("users", userService.getAll());
		
		return "/userList"; // -> /WEB-INF/pages/users/list.jsp
	}
	
	@RequestMapping("/add")
	public String addPage() {
		return "/userAdd"; // -> /WEB-INF/pages/users/add.jsp
	}


	@RequestMapping("/insert")
	public String insert(User user) {
//		log.debug("account={} , name={}",account, name);
//		
//		User user = new User();
//		user.setAccount(account);
//		user.setName(name);
		
		log.debug("user={}",user);
		
		userService.insert(user);
		
		return "redirect:/users/add";
	}
	
	
	@RequestMapping("/delete")
	public String delete(Long id, Model uiModel) {
		log.debug("to delete id={}",id);
		
		userService.delete(id);
		
		return listPage(uiModel);
	}
	
	
	@RequestMapping("/edit")
	public String editPage(Long id, Model uiModel) {
		
		User user = userService.getOne(id);
		
		uiModel.addAttribute("user", user);
		
		return "/userEdit"; // -> /WEB-INF/pages/users/edit.jsp
	}
	
	@RequestMapping("update")
	public String update(User user, Model uiModel) {
//		User user = new User();
//		user.setId(id);
//		user.setName(name);
		
		userService.update(user);
		
		return editPage(user.getId(), uiModel);
	}
	
	
	
	
	
	
	
	
}
